/*
 * Created by Huang 嵘才 on 19-9-20 下午6:23
 * Copyright (c) 2019. All rights reserved.
 * Last modified 19-9-20 下午6:21
 */

package io.esirong

import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * 线程管理功能模块类
 * Created by 黄嵘才(HuangRc) on 2019/9/20.
 */
object ThreadManager {
    /*
    池管理维护一个可执行线程的线程池作为执行调用者给预的任务
    TODO 可配置不同参数线程池
     */
    /**非核心线程可存活时间*/
    private var keepAliveTime: Long = 60
    /**CPU核数：可为设置核心线程数提供数据参照*/
    private val cpuNum = Runtime.getRuntime().availableProcessors()

    init {
    }

    /**
     * 在线程里执行一个代码段
     *
     * @param runnable {@linkplain Runnable}
     */
    @JvmStatic
    fun execute(runnable: Runnable) {
        ThreadPool.execute(runnable)
    }

    /**
     * 线程池
     */
    private object ThreadPool {
        private var corePoolSize: Int = cpuNum * 2
        private var maximumPoolSize: Int = cpuNum * 2 + 1
        var executor: ThreadPoolExecutor? = null

        /**
         * 在线程里执行一个代码段
         *
         * @param runnable {@linkplain Runnable}
         */
        fun execute(runnable: Runnable) {
            if (executor == null) {
                executor = createDefault()
            }
            executor?.execute(runnable)
        }

        /**
         * 从线程队列中移除对象
         *
         * @param runnable {@linkplain Runnable}
         */
        fun cancel(runnable: Runnable) {
            if (executor != null) {
                executor?.queue?.remove(runnable)
            }
        }

        /**
         * 创建一个默认的线程执行者
         */
        fun createDefault(): ThreadPoolExecutor {
            return ThreadPoolExecutor(
                    corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                TimeUnit.MILLISECONDS,
                LinkedBlockingDeque(1024),
                Executors.defaultThreadFactory(),// 线程工厂(TODO 建议替换其他线程工场，在创建线程标记名称，为追究问题提供指引)
                object : ThreadPoolExecutor.AbortPolicy() {
                }
            )
        }
    }


}

